package map;


public class MyHashBucket {   // 实现 key-value 模型
    public static void main(String[] args) {
        MyHashBucket maHash = new MyHashBucket();
        maHash.put(1,11);
        maHash.put(1,111);
        maHash.put(9,99);
        maHash.put(4,444);
        maHash.put(6,66);
        maHash.put(5,55);
        maHash.put(8,88);
        maHash.put(3,33);
        maHash.put(2,22);
        System.out.println(maHash.get(1));
    }
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
    }
    public Node[] array;
    public int usedSize;
    public static final double LOAD_FACTOR = 0.75;

    public MyHashBucket() {
        array = new Node[8];
    }
    public void put(int key, int val){  // 插入
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null){
            if(cur.key == key){
                cur.val = val;
            }
            cur = cur.next;
        }
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;
        if(LOAD_FACTOR <= calculateLoadFactor()){
            resize();
        }
    }

    private void resize() { // 扩容   ***重点
        Node[] newArray = new Node[2 * array.length];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null){
                Node curNext = cur.next;
                int index = cur.key % newArray.length;
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = curNext;
            }
        }
        array = newArray;
    }

    // 计算负载因子
    private double calculateLoadFactor(){
        return usedSize * 1.0 / array.length;
    }
    public int get(int key){  // 根据key找val
        int index = key % array.length;
        Node node = array[index];
        while (node != null){
            if(node.key == key){
                return node.val;
            }
            node = node.next;
        }
        return -1;
    }
}
